//配置路由
// 引入仓库
import store from "@/store";
import Vue from "vue";
import VueRouter from "vue-router";

// 引入路由组件
import routes from "./routes";

// 使用插件
Vue.use(VueRouter);

// 保存VueRouter原型对象的push
let originPush = VueRouter.prototype.push;
let originReplace = VueRouter.prototype.replace;

// 重写push|replace
VueRouter.prototype.push = function (location, resolve, reject) {
  if (resolve && reject) {
    originPush.call(this, location, resolve, reject);
  } else {
    originPush.call(
      this,
      location,
      () => {},
      () => {}
    );
  }
};

VueRouter.prototype.replace = function (location, resolve, reject) {
  if (resolve && reject) {
    originReplace.call(this, location, resolve, reject);
  } else {
    originReplace.call(
      this,
      location,
      () => {},
      () => {}
    );
  }
};

// 配置路由
let router = new VueRouter({
  // 配置路由
  routes,
  // 配置路由滚动行为
  scrollBehavior(to, from, savedPosition) {
    // 返回y 竖直方向滚动条
    return {
      y: 0,
    };
  },
});

// 全局守卫:前置守卫
router.beforeEach(async (to, from, next) => {
  // 判断token
  let token = store.state.user.token;

  let name = store.state.user.userInfo.name;
  if (token) {
    if (to.path == "login") {
      next("/home");
    } else {
      // 已经登录了
      if (name) {
        next();
      } else {
        try {
          // 获取用户信息在首页展示
          await store.dispatch("getUserInfo");
          next();
        } catch (error) {
          // token过期,先清除存储的用户信息，在登录
          store.dispatch("userLogout");
          next("/login");
        }
      }
    }
  } else {
    // 未登录 不能进入那个路由
    let toPath = to.path;
    if (
      toPath.indexOf("/trade") != -1 ||
      toPath.indexOf("/pay") != -1 ||
      toPath.indexOf("/center") != -1
    ) {
      next("/login?redirect=" + toPath);
    }
    next();
  }
});

export default router;
